/* eslint-disable eqeqeq */
/* eslint-disable array-callback-return */
/* eslint-disable no-param-reassign */
/* eslint-disable no-unused-vars */
/* eslint-disable no-return-assign */
/* eslint-disable consistent-return */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable react/no-unused-state */
import React from 'react';
import { connect } from 'dva';
import { Form, Icon as LegacyIcon } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, message, Row, Col, Spin, Tree } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import { urlParse, matchDict } from '@/utils/utils';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { TreeNode } = Tree;
@connect(({ loading, role }) => ({
  loading: loading.models.role,
  role,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dictList: ['ROLE_TYPE'],
      ROLE_TYPE: [],
      systemList: [],
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      sysId: '',
      selectSysInfo: null,
      roleId: '',
      dataInfo: {},
      dataTrees: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const roleId = urlParse(this.props.location.search).roleId
      ? urlParse(this.props.location.search).roleId
      : this.state.roleId;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['ROLE_TYPE'],
    }).then(dict => {
      dispatch({
        type: 'role/listBaseSys',
        payload: {},
      }).then(response => {
        if (response.success && response.data.length) {
          this.setState({ systemList: response.data });
          dispatch({
            type: 'role/getBaseRole',
            payload: {
              roleId,
            },
          }).then(res => {
            if (res.success && res.data) {
              this.setState({
                dataTrees: res.data.baseFunction,
              });
              if (res.data.sysId) {
                res.data.sysName = '';
                res.data.roleType = matchDict(dict.ROLE_TYPE, res.data.roleType);
                response.data.forEach(s => {
                  if (s.sysId == res.data.sysId) {
                    return (res.data.sysName = s.sysName);
                  }
                });
                const expandedKeys = [];
              }
              if (res.data.baseFunction) {
                let newTreeData = [];
                const toTreeData = treeData => {
                  const arr = [...treeData];
                  arr.map(item => {
                    item.key = item.functionId;
                    item.title = item.functionName;
                    item.isLeaf = item.functionType === 2;
                    if (Object.keys(item).includes('childs')) {
                      item.children = item.childs;
                      toTreeData(item.childs);
                    }
                  });
                  return arr;
                };
                newTreeData = [...toTreeData(res.data.baseFunction)];
                const expandedKeys = [];
                const checkedKeys = [];
                const getCheckedId = treeData => {
                  treeData.forEach(item => {
                    if (Object.keys(item).includes('childs')) {
                      getCheckedId(item.childs);
                      expandedKeys.push(item.functionId);
                    } else {
                      checkedKeys.push(item.functionId);
                    }
                  });
                };
                getCheckedId(res.data.baseFunction);
                this.setState({ treeData: newTreeData, checkedKeys, expandedKeys });
              }
              this.setState({ dataInfo: res.data });
            } else {
              message.warning(`${res.message || '暂无数据！'}`);
            }
          });
        } else {
          message.warning(`${response.message || '暂无系统数据'}`);
        }
      });
    });
  }

  // 点击展开
  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: true,
    });
  };

  // 树形复选框：选择
  onCheck = (checkedKeys, info) => {
    this.props.form.setFieldsValue({ baseRoleVo: checkedKeys });
    this.setState({ checkedKeys });
    if (info && info.checked) {
      const expandedKeys = [...checkedKeys, ...info.halfCheckedKeys];
      const { dataRef } = info.node.props;
      const { functionType } = dataRef.dataInfo;
      if (!functionType) {
        this.onExpand(expandedKeys);
        setTimeout(() => {
          const checkedKeysArr = [];
          dataRef.children.map(item => {
            checkedKeysArr.push(item.key);
          });
          this.props.form.setFieldsValue({ baseRoleVo: [...checkedKeys, ...checkedKeysArr] });
          this.setState({ checkedKeys: [...checkedKeys, ...checkedKeysArr] });
        }, 500);
      }
    }
  };

  // 动态加载树形数据
  onLoadData = treeNode => {
    const functionId = treeNode.props.dataRef.key;
    return new Promise(resolve => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      setTimeout(() => {
        resolve();
      }, 500);
    });
  };

  // 树形节点
  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            title={item.title}
            key={item.key}
            dataRef={item}
            icon={({ expanded }) => (
              <LegacyIcon type={expanded ? 'folder-open' : 'folder'} theme="filled" />
            )}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          {...item}
          dataRef={item}
          icon={({ expanded }) => (
            <LegacyIcon type={expanded ? 'folder-open' : 'folder'} theme="filled" />
          )}
        />
      );
    });

  render() {
    const { treeData, expandedKeys, autoExpandParent, checkedKeys, dataInfo } = this.state;
    const {
      loading,
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <PageHeaderWrapper>
        <Spin tip="loading..." spinning={loading}>
          <Card title="角色详情">
            <Form className={styles.controlWrapper}>
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="角色名称">
                    <span>{dataInfo.roleName}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="角色类型">
                    <span>{dataInfo.roleTypeName}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="所属系统">
                    <span>{dataInfo.sysName}</span>
                  </FormItem>
                </Col>
              </Row>
              {treeData.length ? (
                <Row>
                  <Col span={17} offset={1}>
                    <FormItem {...formItemLayout} label="菜单授权">
                      {getFieldDecorator('baseRoleVo', {
                        rules: [{ required: false, message: '请选择' }],
                      })(
                        <Tree showIcon showLine autoExpandParent defaultExpandedKeys={expandedKeys}>
                          {this.renderTreeNodes(treeData)}
                        </Tree>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              ) : null}
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="备注">
                    <span>{dataInfo.remark}</span>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Card>
          <FooterToolbar style={{ width: '100%' }}>
            <Button type="primary" onClick={() => router.push('/systemmanage/role/index')}>
              关闭
            </Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
export default BasicForm;
